<template>
  <div id="advertising-create" class="Row_content" style="width:560px;">
    <Form ref="formInline" :model="formInline" :rules="ruleValidate" :label-width="110">
      <FormItem label="广告名称：" prop="adName">
        <Input
          v-model="formInline.adName"
          placeholder="请输入"
          class="select-shop-item"
          :maxlength="15"
          @on-keyup="filterName"
        ></Input>
      </FormItem>
      <FormItem label="广告位：" prop="adPlaceId">
        <Select v-model="formInline.adPlaceId" class="select-shop-item" clearable>
          <Option
            @click.native="selectadPlace(item)"
            v-for="item in adPlaceList"
            :value="item.adPlaceId"
            :key="item.adPlaceId"
          >{{ item.adPlaceName }}</Option>
        </Select>
      </FormItem>
      <FormItem label="广告位类型：" prop="adPlaceType">
        <p>{{ formInline.adPlaceType===0?"Banner":formInline.adPlaceType===1?"启动页全屏":formInline.adPlaceType===2?"通栏":"" }}</p>
      </FormItem>
      <FormItem label="投放类型：" prop="adType">
        <RadioGroup v-model="formInline.adType" @on-change="selectadType">
          <Radio label="0">按品牌</Radio>
          <Radio label="1">按门店</Radio>
        </RadioGroup>
      </FormItem>
      <FormItem label="投放品牌：" prop="relaIds" v-if="formInline.adType=='0'">
        <Select
          v-model="formInline.relaIds"
          :max-tag-count="1"
          :max-tag-placeholder="maxTagPlaceholder"
          filterable
          multiple
          class="select-shop-item"
        >
          <Option
            v-for="(item, index) in brandList"
            :value="item.brandId"
            :key="index"
          >{{ item.brandName }}</Option>
        </Select>
      </FormItem>
      <FormItem label="投放门店：" prop="relaIds" v-if="formInline.adType=='1'">
        <vueTreeselectChoice
          :multiple="true"
          :width="280"
          ref="vueTreeselectChoice"
          @input="handleShop"
          permissionCode="moms:globalsetting:adcreate"
          v-model="formInline.relaIds"
        ></vueTreeselectChoice>
      </FormItem>
      <FormItem label="展示时间：" prop="beginAt">
        <DatePicker
          :value="formInline.datetime"
          format="yyyy-MM-dd"
          :options="options3"
          type="daterange"
          split-panels
          class="select-shop-item"
          @on-change="selectTime"
        ></DatePicker>
      </FormItem>
      <FormItem label="广告素材：" prop="mediaUrl" class="upload-img">
        <Row type="flex" align="top">
          <Col>
            <Upload
              ref="upload"
              :format="formInline.adPlaceType===1?['jpg','png','mp4']:['jpg','png']"
              :max-size="10240"
              :on-success="handleSuccess"
              :on-format-error="handleFormatError"
              :on-exceeded-size="handleMaxSize"
              type="drag"
              :show-upload-list="false"
              :action="$config.uploadImg"
              style="display: inline-block;width:96px;height:96px;"
            >
               <img
                v-if="!formInline.mediaUrl"
                :src="defaultUrl"
                style="display: inline-block;width:96px;height:96px;vertical-align: top;"
                alt
              />
              <img
                v-if="mediaUrlType===0 && formInline.mediaUrl"
                :src="formInline.mediaUrl?formInline.mediaUrl:defaultUrl"
                style="display: inline-block;width:96px;height:96px;vertical-align: top;"
                alt
              />
              <video
                v-if="mediaUrlType===1 && formInline.mediaUrl"
                :src="formInline.mediaUrl?formInline.mediaUrl:defaultUrl"
                style="display: inline-block;width:96px;height:96px;vertical-align: top;"
              ></video>
            </Upload>
            <p v-if="formInline.mediaUrl && imgloaded" class="replace_tit" @click="delmediaUrl">删除</p>
          </Col>
          <!-- <Col>
            <div
              style="width:118px;height:72px;line-height:18px;color: #464C5B;margin-left:24px;"
            >支持格式：.jpg、.png规格：128px*128px大小：≤50K</div>
          </Col>-->
        </Row>
      </FormItem>
      <FormItem label="跳转链接：" prop="jumpUrl">
        <Input v-model="formInline.jumpUrl" placeholder="请输入" class="select-shop-item"></Input>
      </FormItem>
      <FormItem>
        <Button type="primary" class="btn" :disabled="isDisabled" @click="handleSubmit">确定</Button>
        <Button class="btn" style="margin-left: 24px" @click="closePage">取消</Button>
      </FormItem>
    </Form>
  </div>
</template>

<script>
import { routeEqual } from '@/libs/util'
import { getBrandList } from '@/api/merchant.js'
import { getadPlaceList, adSave } from '@/api/advertising/index'
import vueTreeselectChoice from '@/components/vue-treeselect-choice'
export default {
  name: 'advertising_create',
  components: { vueTreeselectChoice },
  data () {
    const validateRelaIdsCheck = (rule, value, callback) => {
      if (value.length === 0) {
        if (parseInt(this.formInline.adType) === 1) {
          callback(new Error('请选择投放门店'))
        } else if (parseInt(this.formInline.adType) === 0) {
          callback(new Error('请选择投放品牌'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    return {
      merchantId: this.$store.state.user.merchantId,
      submitLock: false,
      isDisabled: false,
      adPlaceList: [], // 广告位
      brandList: [], // 品牌列表
      mediaUrlType: 0,
      formInline: {
        adName: '', // 广告名称
        adPlaceId: '', // 广告位id
        adPlaceType: '',
        adType: '0',
        mediaUrl: '',
        relaIds: '',
        datetime: [],
        jumpUrl: '', // 跳转链接
        beginAt: '', // 生效开始时间 yyyy-MM-dd HH:mm:ss
        endAt: '' // 生效结束时间 yyyy-MM-dd HH:mm:ss
      },
      imgloaded: false,
      defaultUrl: require('@/assets/images/add.png'),
      ruleValidate: {
        adName: [{ required: true, message: '广告名称不能为空', trigger: 'blur' }],
        adPlaceId: [{ required: true, message: '请选择广告位', trigger: 'change' }],
        adType: [{ required: true, message: '请选择投放类型', trigger: 'change' }],
        relaIds: [{ required: true, type: 'array', validator: validateRelaIdsCheck, trigger: 'change' }],
        beginAt: [{ required: true, message: '请选择展示时间', trigger: 'blur' }],
        mediaUrl: [{ required: true, message: '广告素材不能为空', trigger: 'change' }]
      },
      options3: {
        disabledDate (date) {
          return date && date.valueOf() < Date.now() - 86400000
        }
      }
    }
  },
  created () {
    this.getadPlaceList()
    this.getBrandList()
  },
  methods: {
    filterName () {
      this.formInline.adName = this.formInline.adName.replace(/\s+/g, '')
    },
    async handleShop () {
      const ids = await this.$refs.vueTreeselectChoice.getShopId()
      this.formInline.relaIds = ids
      this.$refs['formInline'].validate(valid => {})
    },
    // 查询品牌列表
    getBrandList () {
      getBrandList({
        merchantId: this.merchantId // 商户id
      })
        .then(res => {
          const result = res.data || {}
          if (result.status === 200) {
            this.brandList = result.data
          } else {
            this.brandList = []
            this.$Message.error(`${result.error}`)
          }
        })
        .catch(err => {
          this.$Message.error(`${err}`)
        })
    },
    // 查询广告位列表
    getadPlaceList () {
      getadPlaceList({
        merchantId: this.merchantId, // 商户id
        channelId: '', // 渠道ID
        adPlaceType: '', // 广告位类型
        adPlaceName: '', // 广告位名称
        creatorName: '', // 创建人名称
        createAtStart: '', // 创建时间起始
        createAtEnd: '' // 创建时间结束
      })
        .then(res => {
          if (res.data.status === 200) {
            if (res.data.totalCount > 0) {
              this.adPlaceList = res.data.data
            } else {
              this.adPlaceList = []
            }
          } else {
            this.$Message.error(`${res.data.error}`)
          }
        })
        .catch(error => {
          this.$Message.error(`${this.showError(error)}`)
        })
    },
    // 选择广告位
    selectadPlace (e) {
      this.formInline.adPlaceType = e.adPlaceType
    },

    // 选择投放方式
    selectadType (e) {
      this.formInline.adType = e
      this.formInline.relaIds = []
      this.$refs['formInline'].validate(valid => {})
    },
    maxTagPlaceholder (num) {
      return '...'
    },
    // 选择创建时间
    selectTime (e) {
      this.formInline.beginAt = e[0]
      this.formInline.endAt = e[1]
      this.options3 = {
        disabledDate (date) {
          return date && date.valueOf() < Date.now() - 86400000
        }
      }
    },
    handleMaxSize (file) {
      this.$Message.warning('上传的文件大小不能超过10MB')
    },
    handleFormatError (file) {
      this.$Message.warning('上传的文件格式错误')
    },
    handleSuccess (response, file, fileList) {
      var _this = this
      if (response.errr_msg !== null && response.full_img_url === null) {
        this.$Message.warning(response.errr_msg)
      }
      var img = new Image()
      img.src = response.full_img_url
      // let temsrc = _this.formInline.mediaUrl
      _this.formInline.mediaUrl = response.full_img_url
      if (_this.formInline.mediaUrl.indexOf('.mp4') > -1) {
        this.mediaUrlType = 1
      } else {
        this.mediaUrlType = 0
      }
      // img.onload = function() {
      // if (img.width !== 128 || img.height !== 128) {
      //   _this.$Message.warning('上传的图片规格不符')
      //   _this.formInline.mediaUrl = temsrc
      // } else {
      _this.imgloaded = true
      // _this.formInline.mediaUrl = response.full_img_url
      // }
      // }
    },
    delmediaUrl () {
      this.formInline.mediaUrl = ''
      this.imgloaded = false
    },
    handleSubmit () {
      this.$refs['formInline'].validate(valid => {
        if (valid) {
          this.isDisabled = true
          adSave({
            merchantId: this.merchantId, // 商户id
            adType: this.formInline.adType, // 广告类型 0 按品牌、1 按门店
            mediaUrl: this.formInline.mediaUrl, // 多媒体的url
            creatorName: this.$store.state.user.userName, // 创建名称
            creator: this.$store.state.user.userId, // 创建人
            relaIds: this.formInline.relaIds, // 关联ids
            beginAt: this.formInline.beginAt + ' 00:00:00', // 生效开始时间 yyyy-MM-dd HH:mm:ss
            endAt: this.formInline.endAt + ' 23:59:59', // 生效结束时间 yyyy-MM-dd HH:mm:ss
            adPlaceId: this.formInline.adPlaceId, // 广告位id
            adName: this.formInline.adName, // 广告名称
            jumpUrl: this.formInline.jumpUrl // 跳转的url
          }).then(res => {
            if (res.data.status === 200) {
              this.isDisabled = false
              this.$Message.success('新增广告成功')
              this.closePage()
            } else {
              this.isDisabled = false
              this.$Message.error(`${res.data.error}`)
            }
          })
        }
      })
    },
    closePage () {
      this.$store.commit('closeTag', this.$route)
      this.$store.commit(
        'setTagNavList',
        this.$store.state.app.tagNavList.filter(item => !routeEqual(this.$route, item))
      )
      this.$nextTick(() => {
        this.$router.push({
          name: 'advertising_list'
        })
      })
    }
  }
}
</script>
<style lang='less'>
#advertising-create {
  .ivu-date-picker {
    width: 280px;
    .ivu-date-picker-editor {
      width: 280px;
    }
  }
  .replace_tit {
    position: absolute;
    left: 0;
    top: 72px;
    width: 96px;
    height: 24px;
    line-height: 24px;
    text-align: center;
    opacity: 0.8;
    background: #ed4014;
    color: #fff;
  }
  .vueTreeselectShop .vue-treeselect__multi-value-label {
    max-width: 150px;
  }
}
</style>
